package com.yz.admin.controller;

import com.yz.admin.pojo.User;
import com.yz.admin.pojo.UserStatus;
import com.yz.admin.service.AdminService;
import com.yz.admin.vo.PageVo;
import com.yz.admin.vo.SubmitVo;
import com.yz.common.pojo.DbLink;
import com.yz.common.pojo.DbType;
import com.yz.common.pojo.LogSheet;
import com.yz.common.pojo.Task;
import com.yz.common.utils.JdbcUtils;
import com.yz.common.utils.PageUtil;
import com.yz.common.utils.Result;
import com.yz.common.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/adminController")
@CrossOrigin
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 查看所有账号
     * @return
     */
    @GetMapping("/findAllUser")
    public Result findAllUser(){
        List<User> userList = adminService.findAllUser(UserStatus.CAN_USE.toString());
        if(userList!=null){
            return new Result(true, StatusCode.OK,"查询成功",userList,"查看所有账号");
        }
        return new Result(false,StatusCode.ERROR,"查询失败","查看所有账号");
    }


    /**
     * 删除账号
     * @param id
     * @return
     */
    @GetMapping("/deleteUserById/{id}")
    public Result deleteUserById(@PathVariable("id") Integer id){
        int result = adminService.deleteUserById(id,UserStatus.CAN_NOT_USE.toString());
        if(result==1){
            return new Result(true, StatusCode.OK,"删除成功","删除id为:"+id+"的账号");
        }
        return new Result(false,StatusCode.ERROR,"删除失败","删除id为:"+id+"的账号");
    }

    /**
     * 修改权限
     * @param user
     * @return
     */
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        Result result = adminService.updateUser(user);
        return result;
    }


    /**
     * 查看任务
     * @return
     */
    @GetMapping("/findAllTask")
    public Result findAllTask(){
        List<Task> tasks=adminService.findAllTask();
        if(tasks!=null){
            return new Result(true,StatusCode.OK,"查询成功",tasks,"查看任务");
        }
        return new Result(true,StatusCode.OK,"查询失败","查看任务");
    }


    /**
     * 审核任务
     * @param
     * @param
     * @return
     */
    @PostMapping("/updateTaskStatus")
    public Result updateTaskStatus(@RequestBody SubmitVo submitVo){
        int result = adminService.updateTaskStatus(submitVo);
        if(result==1){
            return new Result(true, StatusCode.OK,"审核成功","审核id为:"+submitVo.getId()+"的任务");
        }
        return new Result(false,StatusCode.ERROR,"审核失败","审核id为:"+submitVo.getId()+"的任务");
    }


    /**
     * 添加数据库连接
     * @param dbLink
     * @return
     */
    @Transactional
    @PostMapping("/addDatabaseLink")
    public Result addDatabaseLink(@RequestBody DbLink dbLink){

        try {
            Result result = adminService.addDatabaseLink(dbLink);
            if(result!=null){
                return new Result(false, StatusCode.ERROR,"出现异常","出现异常");
            }
            //adminService.importDatabase(dbLink.getUsername(),dbLink.getPassword(),dbLink.getId());
            return new Result(true, StatusCode.OK,"添加成功","添加数据库连接");
        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR,"出现异常","出现异常");
        }

    }

    /**
     * 获取所有数据库连接类型
     * @return
     */
    @GetMapping("/getAllDatabaseType")
    public Result getAllDatabaseType(){
        List<DbType> list= adminService.getAllDatabaseType();
        if(list!=null){
            return new Result(true, StatusCode.OK,"查询成功",list,"获取所有数据库连接类型");
        }
        return new Result(false,StatusCode.ERROR,"查询失败","获取所有数据库连接类型");
    }


    /**
     * 导入该连接下所有数据库  1.基本四项  2.查询所有数据库名  3.sql拼接插入
     * @param username
     * @param password
     * @param linkId
     * @return
     */
    public Result importDatabase(String username,String password,Integer linkId){
        DbLink dbLink = adminService.findLinkById(linkId);
        Map map = getMapByDbLink(dbLink, username, password);
        ArrayList<String> databasesArray = new ArrayList<>();
        try {
            List<Map> databases = JdbcUtils.queryData(map, "SHOW DATABASES");

            for (Map database : databases) {

                String[] split = database.toString().split("=");

                databasesArray.add(split[1].substring(0,split[1].length()-1));
            }
            for (String databasesName : databasesArray) {
                adminService.insertDatabase(linkId,username,password,databasesName);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return new Result(true, StatusCode.OK,"执行成功","导入该连接下所有数据库");
    }

    /**
     * 查询所有数据库连接
     * @return
     */
    @GetMapping("getAllDbLink")
    public Result getAllDbLink(){
        List<DbLink> dbLinkList = adminService.getAllDbLink();
        if(dbLinkList!=null){
            return new Result(true, StatusCode.OK,"查询成功",dbLinkList,"查询所有数据库连接");
        }
        return new Result(false,StatusCode.ERROR,"查询失败","查询所有数据库连接");
    }



    /**
     * 删除数据库连接   删除数据库表信息
     * @param linkId
     * @return
     */
    @GetMapping("deleteDbLink/{linkId}")
    public Result deleteDbLink(@PathVariable("linkId") Integer linkId){
        int i = adminService.deleteDbLinkById(linkId);
        if(i!=-1){
            return new Result(true, StatusCode.OK,"删除成功","删除数据库连接id为"+linkId);
        }
        return new Result(false,StatusCode.ERROR,"删除失败","删除数据库连接id为"+linkId);
    }

    //获取基本四项map
    public Map getMapByDbLink(DbLink dbLink,String username,String password){
        StringBuffer url = new StringBuffer();
        // ==1 说明是mysql
        if(dbLink.getDbType() == 1){
            url.append("jdbc:mysql://");
            url.append(dbLink.getIp());
            url.append(":");
            url.append(dbLink.getPort());
            url.append("/mysql?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=UTC");
        }

        Map map=new HashMap();
        map.put("driver", dbLink.getDriver());
        map.put("url", url.toString());
        map.put("username", username);
        map.put("pass", password);

        return map;
    }


    /**
     * 查看日志
     * @return
     */
    @GetMapping("/findLogCount")
    public Result findLogCount(){
        Integer count =adminService.findLogCount();
        return new Result(true,StatusCode.OK,"查询成功",count,"查询日志记录总数");
    }

    /**
     * 查看日志
     * @return
     */
    @GetMapping("/findAllLog/{pageNum}")
    public Result findAllLog(@PathVariable("pageNum") Integer pageNum){
        Integer count =adminService.findLogCount();
        PageUtil pageUtil = new PageUtil(pageNum+"",count,10);
        List<LogSheet> tasks=adminService.findAllLog(pageNum,10);
        PageVo pageVo = new PageVo(tasks,pageUtil);
        if(tasks!=null){
            return new Result(true,StatusCode.OK,"查询成功",pageVo,"查看日志");
        }
        return new Result(true,StatusCode.OK,"查询失败","查看日志");
    }
}
